<?php

namespace app\admin\controller;

use app\admin\model\Question;
use app\common\controller\Backend;
use app\common\model\ExamPaperQuestion;
use think\exception\HttpResponseException;
use think\Db;
use think\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\exception\DataNotFoundException;
use think\Exception;

/**
 * 考试组卷
 *
 * @icon fa fa-circle-o
 */
class Exampaper extends Backend
{

    /**
     * Exampaper模型对象
     * @var \app\admin\model\Exampaper
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Exampaper;
        $this->view->assign("modeList", $this->model->getModeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }
        
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $this->valid($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
             
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    # 保存试卷固定题目
                    if ($params['mode'] == 'FIX') {
                        $this->saveExamFixQuestion($this->model, $params);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $this->valid($params);
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    # 保存试卷固定题目
                    if ($params['mode'] == 'FIX') {
                        $this->saveExamFixQuestion($row, $params, 'edit');
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        # 编辑回显 固定选题 考试模式
        $row['questions'] = Question::getExamFixListByPaperId($row['id'], ['mock']);
        # 编辑回显固定选题模式
        $row['mode'] = 'FIX';
        $this->view->assign("row", $row);
       
        return $this->view->fetch();
    }
    

    protected function saveExamFixQuestion($exampaper, $params, $method = 'add')
    {
        # 固定选题
        $examPaperQuestion = (new ExamPaperQuestion());
        if ($method == 'edit') {
            $examPaperQuestion::where('paper_id', $exampaper['id'])->delete();
        }
        $questions = $params['questions'];
        $data = ['exampaper' => $exampaper, 'questions' => $questions];
        $dd = $this->model->addFixExamQuestion($data);
        return;
    }

    /**
     * 验证码规则
     * @param mixed &$params 
     * @return void 
     * @throws HttpResponseException 
     */
    protected function valid(&$params)
    {
        if ($params['pass_score'] > $params['total_score']) {
            $this->error('及格分数不能大于总分');
        }

        $params['start_time'] = $params['start_time'] ?: 0;
        $params['end_time']   = $params['end_time'] ?: 0;

        if ($params['start_time']) {
            if ($params['start_time'] > $params['end_time']) {
                $this->error('开始时间不能大于结束时间');
            }
            if (strtotime($params['start_time']) < time()) {
                $this->error('开始时间不能小于当前时间');
            }
        }
        if ($params['end_time']) {
            if (!$params['start_time']) {
                $this->error('请先选择开始时间');
            }
        }
        // 固定选题模式
        if ($params['mode'] == 'FIX') {
            $params['questions'] = json_decode($params['questions'], true);
            if (!$params['questions']) {
                $this->error('请先选择题目');
            }
            if (count($params['questions']) < $params['quantity']) {
                $this->error('题目数量不能大于题目总数');
            }
        }
        $limit_time = 0;
        if ($params['limit_time_hour']) {
            $limit_time += $params['limit_time_hour'] * 60 * 60;
        }
        if ($params['limit_time_minute']) {
            $limit_time += $params['limit_time_minute'] * 60;
        }
        $params['limit_time'] = $limit_time;
        //    if ($params['is_prevent_switch_screen']) {
        //        if (empty($params['switch_screen_count']) || $params['switch_screen_count'] < 1) {
        //            $this->error('切屏次数不能小于1');
        //        }
        //        if (empty($params['switch_screen_second']) || $params['switch_screen_second'] < 1) {
        //            $this->error('切屏认定秒数不能小于1');
        //        }
        //    }
    }



    /**
     * 真删除
     * @param mixed $ids 
     * @return void 
     * @throws HttpResponseException 
     * @throws DbException 
     * @throws ModelNotFoundException 
     * @throws DataNotFoundException 
     */
    public function destroy($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post('ids');
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $item) {
                ExamPaperQuestion::whereIn('paper_id',$ids)->delete();
                $count += $item->delete(true);
            }
            Db::commit();
        } catch (PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }



    


}
